import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import '../services/camera_service.dart';
import '../services/ocr_service.dart';
import '../services/database_service.dart';
import '../models/business_card.dart';
import 'business_card_edit_screen.dart';

class CameraScreen extends StatefulWidget {
  const CameraScreen({super.key});

  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  final CameraService _cameraService = CameraService();
  final OCRService _ocrService = OCRService();
  final DatabaseService _databaseService = DatabaseService();
  
  bool _isInitialized = false;
  bool _isProcessing = false;
  String? _capturedImagePath;

  @override
  void initState() {
    super.initState();
    _initializeCamera();
  }

  Future<void> _initializeCamera() async {
    final success = await _cameraService.initializeCamera();
    setState(() {
      _isInitialized = success;
    });
    
    if (!success) {
      _showErrorDialog('相机初始化失败，请检查权限设置');
    }
  }

  Future<void> _takePicture() async {
    if (!_isInitialized) return;

    setState(() {
      _isProcessing = true;
    });

    try {
      final imagePath = await _cameraService.takePicture();
      if (imagePath != null) {
        setState(() {
          _capturedImagePath = imagePath;
        });
        await _processImage(imagePath);
      } else {
        _showErrorDialog('拍照失败，请重试');
      }
    } catch (e) {
      _showErrorDialog('拍照错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _pickImageFromGallery() async {
    setState(() {
      _isProcessing = true;
    });

    try {
      final imagePath = await _cameraService.pickImageFromGallery();
      if (imagePath != null) {
        setState(() {
          _capturedImagePath = imagePath;
        });
        await _processImage(imagePath);
      } else {
        _showErrorDialog('选择图片失败');
      }
    } catch (e) {
      _showErrorDialog('选择图片错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _processImage(String imagePath) async {
    try {
      // 识别文字
      final recognizedText = await _ocrService.recognizeTextFromImage(imagePath);
      
      if (recognizedText.isEmpty) {
        _showErrorDialog('无法识别图片中的文字，请重新拍摄');
        return;
      }

      // 提取名片信息
      final businessCard = await _ocrService.extractBusinessCardInfo(imagePath, recognizedText);
      
      if (businessCard == null) {
        _showErrorDialog('无法从图片中提取名片信息，请手动编辑');
        // 创建一个空的名片让用户手动编辑
        final emptyCard = BusinessCard(
          name: '',
          company: '',
          position: '',
          phone: '',
          email: '',
          address: '',
          website: '',
          imagePath: imagePath,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
          notes: '识别的文字:\n$recognizedText',
        );
        _navigateToEditScreen(emptyCard);
        return;
      }

      // 导航到编辑界面
      _navigateToEditScreen(businessCard);
    } catch (e) {
      _showErrorDialog('处理图片错误: $e');
    }
  }

  void _navigateToEditScreen(BusinessCard card) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BusinessCardEditScreen(card: card),
      ),
    );
    
    if (result == true) {
      Navigator.pop(context, true);
    }
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('錯誤'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('確定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('扫描名片'),
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.photo_library),
            onPressed: _pickImageFromGallery,
          ),
        ],
      ),
      body: Container(
        color: Colors.black,
        child: _isInitialized
            ? _buildCameraView()
            : _buildLoadingView(),
      ),
    );
  }

  Widget _buildLoadingView() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Colors.white),
          SizedBox(height: 20),
          Text(
            '正在初始化相机...',
            style: TextStyle(color: Colors.white, fontSize: 16),
          ),
        ],
      ),
    );
  }

  Widget _buildCameraView() {
    final cameraController = _cameraService.cameraController;
    if (cameraController == null || !cameraController.value.isInitialized) {
      return const Center(
        child: Text(
                      '相机未初始化',
          style: TextStyle(color: Colors.white, fontSize: 16),
        ),
      );
    }

    return Stack(
      children: [
        // 相机预览
        Center(
          child: AspectRatio(
            aspectRatio: cameraController.value.aspectRatio,
            child: CameraPreview(cameraController),
          ),
        ),
        // 拍照框
        _buildCaptureFrame(),
        // 底部控制按钮
        _buildBottomControls(),
        // 处理中遮罩
        if (_isProcessing) _buildProcessingOverlay(),
      ],
    );
  }

  Widget _buildCaptureFrame() {
    return Center(
      child: Container(
        width: 300,
        height: 200,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.white,
            width: 2,
          ),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Stack(
          children: [
            // 四个角的指示器
            Positioned(
              top: 0,
              left: 0,
              child: Container(
                width: 20,
                height: 20,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                width: 20,
                height: 20,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(10),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              child: Container(
                width: 20,
                height: 20,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(10),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 0,
              right: 0,
              child: Container(
                width: 20,
                height: 20,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    bottomRight: Radius.circular(10),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomControls() {
    return Positioned(
      bottom: 50,
      left: 0,
      right: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 相册按钮
          GestureDetector(
            onTap: _pickImageFromGallery,
            child: Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.photo_library,
                color: Colors.white,
                size: 30,
              ),
            ),
          ),
          // 拍照按钮
          GestureDetector(
            onTap: _takePicture,
            child: Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.grey,
                  width: 4,
                ),
              ),
              child: const Icon(
                Icons.camera_alt,
                color: Colors.black,
                size: 40,
              ),
            ),
          ),
          // 切换相机按钮
          GestureDetector(
            onTap: () async {
              await _cameraService.switchCamera();
            },
            child: Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.flip_camera_ios,
                color: Colors.white,
                size: 30,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProcessingOverlay() {
    return Container(
      color: Colors.black.withOpacity(0.7),
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 20),
            Text(
              '正在处理图片...',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _cameraService.dispose();
    _ocrService.dispose();
    super.dispose();
  }
}
